// SPDX-FileCopyrightText: 2025 citrus Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

#include "backend_window.h"

BackendWindow::BackendWindow(int width, int height) {
    const uint64_t usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
    AImageReader_newWithUsage(width, height, AIMAGE_FORMAT_RGBA_8888, usage, 1, &m_image_reader);
    struct AImageReader_ImageListener imageListener = { this, [](void* context, AImageReader* reader) {
        return static_cast<BackendWindow*>(context)->OnImageAvailable(reader);
    }};
    AImageReader_setImageListener(m_image_reader, &imageListener);
}

BackendWindow::~BackendWindow()
{
    if (m_image_reader)
    {
        AImageReader_delete(m_image_reader);
        m_image_reader = nullptr;
    }
}

void BackendWindow::OnImageAvailable(AImageReader *reader) {
    AImage* image = nullptr;
    AImageReader_acquireNextImage(reader, &image);
    if (image) {
        AHardwareBuffer* hardwareBuffer = nullptr;
        AImage_getHardwareBuffer(image, &hardwareBuffer);
        OnImageUpdate(hardwareBuffer);
        AImage_delete(image);
    }
}

ANativeWindow *BackendWindow::getNativeWindow() {
    ANativeWindow* window = nullptr;
    AImageReader_getWindow(m_image_reader, &window);
    return window;
}